#include "CTableConfig.h"

CTableConfig::CTableConfig(QObject *parent)
    : AbsTable("config",parent)
{
    if(!this->exisit()){
        createTable();

        //创建默认数据
        addRow(StConfig("IsTop","0"));
        addRow(StConfig("SelectedId","0"));
        addRow(StConfig("DefaultPort","9009"));
        addRow(StConfig("TextCode","UTF-8"));
        addRow(StConfig("MaxLine","10000"));
        addRow(StConfig("LongPress","1"));
        addRow(StConfig("Span","100"));
        addRow(StConfig("Language","简体中文"));
        addRow(StConfig("Skin","/Skin/userStyle.qss"));
        addRow(StConfig("CurrSkin","0"));
        addRow(StConfig("PrimiaryColor","#1aa3ff"));
        addRow(StConfig("Font","Consolas"));
        addRow(StConfig("FontSize","12"));
    }

    columnNames();
}

CTableConfig *CTableConfig::instance()
{
    static CTableConfig *pInstance = nullptr;
    if(nullptr == pInstance){
        pInstance = new CTableConfig();
    }

    return pInstance;
}

bool CTableConfig::createTable()
{
     QString strSql =   "CREATE TABLE config (     "
                        "   key TEXT PRIMARY KEY "
                        "              UNIQUE      "
                        "              NOT NULL,   "
                        "   value TEXT             "
                        ");                        ";

     return execSql(strSql);
}

bool CTableConfig::addRow(StConfig st)
{
    QString strSql = QString("insert into %1 values('%2','%3')")
            .arg(m_strTableName,st.key,st.value);

    return execSql(strSql);
}

bool CTableConfig::updateValue(QString strKey, QString strValue)
{
    QString strSql = QString("update  %1 set value='%2' where key='%3'")
            .arg(m_strTableName,strValue,strKey);

    return execSql(strSql);
}

bool CTableConfig::updateValue(CTableConfig::Key enmKey, QString strValue)
{
    QMetaEnum meta = QMetaEnum::fromType<Key>();
    QString strKey = QString(meta.valueToKey(enmKey));
    if(strKey.isEmpty()){
        qWarning()<<"key empty!";
        return false;
    }
    return updateValue(strKey,strValue);
}

bool CTableConfig::deleteRow(QString strKey)
{
    QString strSql = QString("delete from %1 where key='%2'")
            .arg(m_strTableName,strKey);

    return execSql(strSql);
}

QString CTableConfig::queryValue(QString strKey)
{
    QString strSql = QString("select value from %1 where key='%2'")
            .arg(m_strTableName,strKey);

    QSqlQuery query(*dbConnection());
    query.prepare(strSql);

    if(exec(query)){
        while(query.next()){
            if(!query.record().isEmpty())
                return query.value(0).toString();
        }
    }
    return "";
}

QString CTableConfig::queryValue(CTableConfig::Key enmKey)
{
    QMetaEnum meta = QMetaEnum::fromType<Key>();
    QString strKey = QString(meta.valueToKey(enmKey));
    return queryValue(strKey);
}
